//
//  LoginViewController.swift
//  osc
//
//  Created by admin on 14/11/1.
//  Copyright (c) 2014年 sinosun. All rights reserved.
//

import UIKit

let login_cell = "login_cell"
class LoginViewController: UIViewController,UIWebViewDelegate{


    
    @IBOutlet var webview: UIWebView!
    var data: NSData?
    var code: String = ""
    var token: TokenM?
    var from: String = ""
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        self.title = "登录"
        setBarButtons()
        self.webview.scalesPageToFit = true
    }
    
    
    override func viewWillAppear(animated: Bool) {
        authorize()
        self.webview.delegate = self

    }
    
    
    func webViewDidFinishLoad(webView: UIWebView){
        var url_str = webview.request?.URL.absoluteString

        if url_str!.hasPrefix("http://my.oschina.net/lucasz") {
            var rangeBegin = url_str?.rangeOfString("code=", options: NSStringCompareOptions.allZeros, range: nil, locale: nil)
            self.code = url_str!.substringFromIndex(rangeBegin!.endIndex)
            var rangeEnd = self.code.rangeOfString("&state", options: NSStringCompareOptions.allZeros, range: nil, locale: nil)
            self.code = self.code.substringToIndex(rangeEnd!.startIndex)
            var parameters = ["client_id":client_id, "client_secret": client_secret, "grant_type": grant_type, "redirect_uri": redirect_uri,"code": self.code,"dataType": dataType]
            getToken(parameters)
        }
        

    }
    
    func authorize(){
        //println("应用通过Webview 将用户引导到 OSChina 三方认证页面 上")
        var parameters = ["response_type":response_type , "client_id": client_id, "state": state, "redirect_uri": redirect_uri]
        HttpClient.loadData(oauth2_authorize, parameters:parameters , success: { () -> Void in
                var baseurl = NSURL(string: baseUrl)
            self.webview.loadData(self.data, MIMEType: "text/html", textEncodingName: "UTF8", baseURL: baseurl)
            }, phaser: { (data) -> Void in
                self.data = data
        })
    }
    
    func getToken(parameters: [String: AnyObject]){
       HttpClient.loadData(oauth2_token, parameters: parameters, success: { () -> Void in
            println("from=\(self.from)登录成功")
        if self.from == "" {
            println("打开应用提示登录!直接回到主页")
            var allTableViewController = self.storyboard?.instantiateViewControllerWithIdentifier("Main") as? UIViewController

            self.navigationController?.pushViewController(allTableViewController!, animated: true)

        }
       }) { (data) -> Void in
            var data_str = NSString(data: data, encoding: NSUTF8StringEncoding)
            println("json=\(data_str)")
            var tokenM = TokenM(JSONDecoder(data))
            TokenManager.addToken(tokenM)
            self.token = tokenM
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    func setBarButtons(){
//        var rigthBarButtonItem = UIBarButtonItem(title: "登录", style: UIBarButtonItemStyle.Bordered, target: self, action: "login:")
        
        var leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Bordered, target: self, action: "cancel:")
        
//        self.navigationItem.rightBarButtonItem = rigthBarButtonItem
        self.navigationItem.leftBarButtonItem = leftBarButtonItem
    }

    
    func cancel(sender: AnyObject){
        self.dismissViewControllerAnimated(true, completion: { () -> Void in
            println("取消")
        })
    }
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
